package cn.edu.buaa.treehole.service;

import cn.edu.buaa.treehole.dao.NameDao;
import cn.edu.buaa.treehole.dao.SignatureDao;
import cn.edu.buaa.treehole.pojo.dao.NameDaoInfo;
import cn.edu.buaa.treehole.service.exception.NameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class NameService {
    private List<String> names = Arrays.asList(defaultNames);
    private boolean usingDefault = true;
    private final NameDao nameDao;

    @Autowired
    public NameService(NameDao nameDao) {
        this.nameDao = nameDao;
    }

    private void init() {
        if (usingDefault) {
            synchronized (NameService.class) {
                if (usingDefault) {
                    List<NameDaoInfo> nameDaoInfoList = null;
                    try {
                        nameDaoInfoList = nameDao.selectAllName();
                    } catch (Exception ignored) {
                    }
                    if (nameDaoInfoList != null && nameDaoInfoList.size() > 0) {
                        String[] tmp = new String[nameDaoInfoList.size()];
                        for (NameDaoInfo nameDaoInfo : nameDaoInfoList) {
                            tmp[nameDaoInfo.getNid()] = nameDaoInfo.getName();
                        }
                        names = Arrays.asList(tmp);
                        usingDefault = false;
                    }
                }
            }
        }
    }

    public String getName(int nid) {
        init();
        if (nid > names.size()) {
            return "#" + String.valueOf(nid);
        }
        return names.get(nid);
    }

    public long getNid(String name) throws NameNotFoundException {
        if (name.charAt(0) == '#') {
            return Long.parseLong(name.substring(1));
        }
        init();
        for (int i = 0; i < names.size(); i++) {
            if (names.get(i).equals(name)) {
                return i;
            }
        }
        throw new NameNotFoundException();
    }

    private final static String[] defaultNames = {
            "Host",
            "Ampere",
            "Bolzano",
            "Cauchy",
            "Darwin",
            "Emily",
            "Frank",
            "Gauss",
            "Harrison",
            "Isaac",
            "Joseph",
            "Kennedy",
            "Luke",
            "Marshal",
            "Nancy",
            "Olivia",
            "Paul",
            "Quentin",
            "Richard",
            "Steve",
            "Tomas",
            "Ulysses",
            "Victor",
            "Warren",
            "Zack",
            "Angel",
            "Benjamin"
    };
}
